/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.controller;


import admin.util.UtilCommon;
import ejb.bean.AccountFacade;
import ejb.entity.Account;
import ejb.entity.Role;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

/**
 *
 * @author Nothing4ever
 */
@Named(value = "loginBean")
@SessionScoped
public class LoginController implements Serializable {

    private static final long serialVersionUID = 1L;
    @EJB
    private AccountFacade accountFacade;
    private Account account;
    private boolean login;
    private String returlUrl;

    /**
     * Creates a new instance of LoginBean
     */
    public LoginController() {
        account = new Account();
        login = false;
    }

    public void login() {
        System.out.println("login");
        setAccount(accountFacade.login(account));
        if (getAccount() == null || !getAccount().getRoleId().getName().equalsIgnoreCase(Role.ROLE_ADMIN)) {
            setAccount(new Account());
            getCommonUtils().showErrorsMessage("msg", null, "The username or password is incorrect!");
            System.out.println("login failed");
        } else {
            System.out.println("login success");
            if (returlUrl == null || returlUrl.isEmpty()) {
                returlUrl = "./admin/home.xhtml";
            }
            setLogin(true);
            getCommonUtils().redirectPage(returlUrl);
        }
    }

    public void logout() {
        setLogin(false);
        setAccount(new Account());
        returlUrl = getCommonUtils().getRequestUri();
        getCommonUtils().redirectPage("../admin/login.xhtml");
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account manager) {
        this.account = manager;
    }

    public boolean isLogin() {
        return login;
    }

    protected void setLogin(boolean login) {
        this.login = login;
    }

    protected AccountFacade getAccountFacade() {
        return accountFacade;
    }

    protected UtilCommon getCommonUtils() {
        return UtilCommon.getInstance();
    }

    public String getReturlUrl() {
        return returlUrl;
    }

    public void setReturlUrl(String returlUrl) {
        this.returlUrl = returlUrl;
    }

    public void checkLogin() {
        if (isLogin()) {
            getCommonUtils().redirectPage("../admin/home.xhtml");
        }
    }
}
